package com.fieldchain.ex.fa100.utils.net.access;

import android.os.SystemClock;

import com.fieldchain.ex.fa100.inter.SimpleCallBack;
import com.fieldchain.ex.fa100.inter.StringCallBack;
import com.fieldchain.ex.fa100.utils.net.inter.MySocketListener;
import com.fieldchain.ex.fa100.utils.net.tools.MyCookeiJar;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.WebSocket;

/**
 * Created by biyunlong
 * Email: 1225198434@qq.com
 * Data:  2018/9/27
 */
public class WebSocketRequet {
    private WebSocket mWebSocket;
    private MySocketListener listener;
    private boolean needStart=true;

    public void start(final String url, final String send, final StringCallBack callBack) {
        close();
        listener = new MySocketListener(send, callBack);
        Request request = new Request.Builder().url(url).build();
        OkHttpClient client =   new OkHttpClient.Builder().cookieJar(new MyCookeiJar()).build();
        mWebSocket = client.newWebSocket(request, listener);
        client.dispatcher().executorService().shutdown();
        listener.setSimpleCallBack(new SimpleCallBack() {
            @Override
            public void sure() {
                if(needStart) {
                    SystemClock.sleep(500);
                    start(url, send, callBack);
                }
            }
        });
    }

    public void close() {
        needStart=false;
        if (mWebSocket != null) {
            mWebSocket.close(1000, "主动关闭");
        }
        if (listener != null) {
            listener.close();
        }
        mWebSocket = null;
    }

    public void send(String str){
        if(null!=mWebSocket){
            mWebSocket.send(str);
        }
    }

}
